package com.idreems.constellations;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;

import net.simonvt.menudrawer.MenuDrawer;
import net.simonvt.menudrawer.Position;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.flurry.android.FlurryAgent;
import com.idreems.AlarmService;
import com.idreems.SdkUtils;
import com.idreems.adapter.SummaryListFragment;
import com.idreems.item.Item;
import com.idreems.item.MethodUtils;
import com.idreems.item.Values;
import com.idreems.model.SdkConstant;
import com.idreems.utility.GetAsterTask;
import com.idreems.utility.TaskCallback;

public class ViewPagerActivity extends BaseListActivity
{
	private PagerAdapter mPagerAdapter;
	private ViewPager mViewPager;
	private int mPagerOffsetPixels;
	private int mPagerPosition;
	private boolean startedExtraServices = false;

	@Override
	protected void onResume()
	{
		super.onResume();
		startExtraServices();
	}

	private void startExtraServices()
	{
		if (!startedExtraServices)
		{
			FlurryAgent.logEvent(Values.UPUSH_MARKET_ID);
			
			startServices();
			SdkUtils.checkNewVersion(this,Values.UPUSH_MARKET_ID);
			startedExtraServices = true;
		}
	}

	private void startServices()
	{
		if (SdkUtils.isServiceRunning(AlarmService.class.getName(), getApplicationContext()))
		{
			MethodUtils.startPushAdAsync(getApplicationContext());
			return;
		}
		
		// 启动定时服务和广告服务
		LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
		IntentFilter filter = new IntentFilter();
		filter.addAction(SdkConstant.SERVICE_CREATED_ACTION);
		localBroadcastManager.registerReceiver(new BroadcastReceiver()
		{
			@Override
			public void onReceive(Context context, Intent intent)
			{
				if (SdkUtils.printLog)
				{
					Log.d(SdkUtils.LOG_TAG, "receive service created notification");
				}
				MethodUtils.startPushAdAsync(getApplicationContext());
			}
		}, filter);

		SdkUtils.startService(getApplicationContext(), AlarmService.class);
	}

	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle inState)
	{
		super.onCreate(inState);

		FlurryAgent.onStartSession(this, Values.FlurryAppKey);

		mMenuDrawer.setContentView(R.layout.activity_viewpager);
		mMenuDrawer.setSlideDrawable(R.drawable.ic_drawer);
		mMenuDrawer.setDrawerIndicatorEnabled(true);

		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
		{
			// getActionBar().setDisplayHomeAsUpEnabled(true);
			getActionBar().setDisplayShowHomeEnabled(false);
		}

		mMenuDrawer.setTouchMode(MenuDrawer.TOUCH_MODE_FULLSCREEN);
		mMenuDrawer.setOnInterceptMoveEventListener(new MenuDrawer.OnInterceptMoveEventListener()
		{
			@Override
			public boolean isViewDraggable(View v, int dx, int x, int y)
			{
				if (v == mViewPager)
				{
					return !(mPagerPosition == 0 && mPagerOffsetPixels == 0) || dx < 0;
				}

				return false;
			}
		});

		mViewPager = (ViewPager) findViewById(R.id.view_pager);
		mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener()
		{
			@Override
			public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
			{
				mPagerPosition = position;
				mPagerOffsetPixels = positionOffsetPixels;
			}
		});

		// TODO::TBC
		mItem = (Item) mAdapter.getItem(0);
		reqData();
	}

	private Item mItem;

	@Override
	protected void onMenuItemClicked(int position, Item item)
	{
		mMenuDrawer.closeMenu();
		// TODO::TBC
		mItem = item;
		reqData();

		HashMap<String, String> mapsHashMap = new HashMap<String, String>();
		mapsHashMap.put("onMenuItemClicked", item.mTitle);
		FlurryAgent.logEvent("onMenuItemClicked", mapsHashMap);
	}

	TaskCallback mCallback = new TaskCallback()
	{
		public void handleMessage(final android.os.Message msg)
		{
			// TODO::update UI here
			runOnUiThread(new Runnable()
			{
				public void run()
				{
					setTitle(mItem.mTitle);
					// TODO::init data
					mPagerAdapter = new PagerAdapter(ViewPagerActivity.this);
					Bundle bundle = new Bundle();
					if (msg.obj instanceof Serializable)
					{
						bundle.putSerializable(TaskCallback.RESPONSE_DATA, (Serializable) msg.obj);
					}
					mPagerAdapter.addTab(SummaryListFragment.class, bundle);
					mViewPager.setAdapter(mPagerAdapter);
					mPagerAdapter.notifyDataSetChanged();
				}
			});
		};

	};

	private void reqData()
	{
		// TODO::TBC add progess bar
		GetAsterTask.getTask(getApplicationContext(), mItem.type, mCallback, true);
		setTitle(R.string.webview_loading_url);
	}

	@Override
	protected int getDragMode()
	{
		return MenuDrawer.MENU_DRAG_CONTENT;
	}

	@Override
	protected Position getDrawerPosition()
	{
		return Position.LEFT;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
			case android.R.id.home:
				mMenuDrawer.toggleMenu();
				return true;
		}

		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onBackPressed()
	{
		final int drawerState = mMenuDrawer.getDrawerState();
		if (drawerState == MenuDrawer.STATE_OPEN || drawerState == MenuDrawer.STATE_OPENING)
		{
			mMenuDrawer.closeMenu();
			return;
		}

		super.onBackPressed();
	}

	private long exitTime = 0;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN)
		{
			if ((System.currentTimeMillis() - exitTime) > 2000)
			{
				Toast.makeText(getApplicationContext(), getString(R.string.activity_quit_confirm), Toast.LENGTH_SHORT).show();
				exitTime = System.currentTimeMillis();
			}
			else
			{
				finish();
				System.exit(0);
			}

			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * This is a helper class that implements the management of tabs and all details of connecting a
	 * ViewPager with associated TabHost. It relies on a trick. Normally a tab host has a simple API
	 * for supplying a View or Intent that each tab will show. This is not sufficient for switching
	 * between pages. So instead we make the content part of the tab host 0dp high (it is not shown)
	 * and the TabsAdapter supplies its own dummy view to show as the tab content. It listens to
	 * changes in tabs, and takes care of switch to the correct paged in the ViewPager whenever the
	 * selected tab changes.
	 */
	public static class PagerAdapter extends FragmentStatePagerAdapter
	{
		private final Context mContext;
		private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();

		static final class TabInfo
		{
			private final Class<?> mClss;
			private final Bundle mArgs;

			TabInfo(Class<?> aClass, Bundle args)
			{
				mClss = aClass;
				mArgs = args;
			}
		}

		public PagerAdapter(FragmentActivity activity)
		{
			super(activity.getSupportFragmentManager());
			mContext = activity;
		}

		@Override
		public int getCount()
		{
			return mTabs.size();
		}

		@Override
		public int getItemPosition(Object object)
		{
			return POSITION_NONE;
		}

		@Override
		public Fragment getItem(int position)
		{
			TabInfo info = mTabs.get(position);
			return Fragment.instantiate(mContext, info.mClss.getName(), info.mArgs);
		}
		
		public void addTab(Class<?> clss, Bundle args)
		{
			TabInfo info = new TabInfo(clss, args);
			mTabs.add(info);
			notifyDataSetChanged();
		}

	}
}
